package com.yztstudy.Controller;

import com.yztstudy.Service.AddressService;
import com.yztstudy.entity.Address;
import com.yztstudy.param.AddressListParam;
import com.yztstudy.param.AddressParam;
import com.yztstudy.param.AddressRemoveParam;
import com.yztstudy.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 地址的表示层
 */

@RestController
@RequestMapping("/user/address")
public class AddressController {

    @Autowired(required = false)
    private AddressService addressService;

    /**
     * TODO 查看某个用户的全部地址
     * @param addressListParam 前端发来的请求参数
     * @param result 校验后的结果
     * @return
     */
    @PostMapping("/list")
    public R list(@RequestBody @Validated AddressListParam addressListParam, BindingResult result)
    {
        // TODO 1.如果校验失败了
        if (result.hasErrors())
        {
            return R.fail("参数异常,查询失败!");
        }

        // TODO 2.校验成功就送到业务逻辑层处理
        return addressService.list(addressListParam);
    }


    /**
     * TODO 新增用户地址
     * @param addressParam 前端发过来的地址对象
     * @param result 校验后的结果
     * @return
     */
    @PostMapping("/save")
    public R save(@RequestBody @Validated AddressParam addressParam, BindingResult result)
    {
        // TODO 1.如果校验失败了
        if (result.hasErrors())
        {
            return R.fail("参数异常,保存失败!");
        }

        // TODO 2.校验成功就送到业务逻辑层处理
        Address address = addressParam.getAdd();
        address.setUserId(addressParam.getUserId());
        return addressService.save(address);
    }


    /**
     * TODO 删除用户的地址
     * @param addressRemoveParam 前端发过来的参数
     * @param result 校验后的结果
     * @return
     */
    @PostMapping("/remove")
    public R remove(@RequestBody @Validated AddressRemoveParam addressRemoveParam, BindingResult result)
    {
        // TODO 1.如果校验失败了
        if (result.hasErrors())
        {
            return R.fail("参数异常,删除失败!");
        }

        // TODO 2.校验成功就送到业务逻辑层处理
        return addressService.remove(addressRemoveParam);
    }
}
